/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utility;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;

/**
 *
 * @author nivri
 */
public class StreamUtil implements Serializable {

    /* @Param: String 
     * return: InputStream
     * com:Transforma un tipo de Dato String a InputStream
     */
    public static InputStream parseStringToInputStream(String file) throws UnsupportedEncodingException {
        InputStream is = new ByteArrayInputStream(decodeBase64AsByteArray(file));
        return is;
    }

    /* @Param: InputStream 
     * return: String
     * com:Transforma un tipo de Dato InputStream a String
     */
    public  static String convertStreamToString(InputStream is) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        copyStream(is, out);
        out.flush();
        is.close();
        return encodeBase64AsString(out.toByteArray());
    }

    /* @Param: byte[] 
     * return: String
     * com:Transforma un tipo de byte[] a String
     */
    public static String encodeBase64AsString(byte[] plain) {
        if (plain == null) {
            return null;
        }
        return new String(Base64.encodeBase64(plain));
    }
    private static final int STREAM_BUFFER_SIZE = 16384; // 16KB

    /* @Param: InputStream  , ouputStream
     * return: void
     * 
     */
    public static void copyStream(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] buffer = new byte[STREAM_BUFFER_SIZE];
        int bytesRead = 0;
        while ((bytesRead = inputStream.read(buffer, 0, STREAM_BUFFER_SIZE)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
    }

    public static byte[] decodeBase64AsByteArray(String encoded) {
        if (encoded == null) {
            return null;
        }
        return decodeBase64(encoded.getBytes());
    }

    public static byte[] decodeBase64(byte[] encoded) {
        if (encoded == null) {
            return null;
        }
        return Base64.decodeBase64(encoded);
    }
}
